package wyp.library.ui.vc;

import wyp.library.tools.WypLog;
import wyp.library.ui.activity.WypActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

public class WypSlidViewController {

	public static final String TAG = WypSlidViewController.class.getSimpleName();

	private WypActivity mActivity;

	private ViewGroup.MarginLayoutParams mMenuLayoutParams;// menu布局的参数，通过此参数来更改leftMargin的值。
	private int mLeftEdge;// menu最多可以滑动到的左边缘。值由menu布局的宽度来定，marginLeft到达此值之后，不能再减少。
	private boolean mIsMenuVisible;
	private View mContentLayout;// 主内容的布局。
	private View mMenuLayout;// menu的布局。

	public WypSlidViewController(WypActivity _activity) {
		super();
		mActivity = _activity;
	}

	public void initView(View __menuView, View _contentView, int _menuPadding) {
		WindowManager _window = (WindowManager) this.mActivity.getSystemService(Context.WINDOW_SERVICE);
		int _screenWidth = _window.getDefaultDisplay().getWidth();
//		mContentLayout = this.mActivity.findViewById(_contentId);
//		mMenuLayout = this.mActivity.findViewById(_menuId);
		mContentLayout = _contentView;
		mMenuLayout = __menuView;
		mMenuLayoutParams = (ViewGroup.MarginLayoutParams) mMenuLayout.getLayoutParams();
		mMenuLayoutParams.width = _screenWidth - _menuPadding;
		mLeftEdge = -mMenuLayoutParams.width;
		mMenuLayoutParams.leftMargin = mLeftEdge;
		mContentLayout.getLayoutParams().width = _screenWidth;
	}

	public void showOrHideMenu() {
		if (mIsMenuVisible == true) {
			new ScrollTask().execute(-30);
		} else {
			new ScrollTask().execute(30);
		}
	}

	private class ScrollTask extends AsyncTask<Integer, Integer, Integer> {

		@Override
		protected Integer doInBackground(Integer... speed) {
			int leftMargin = mMenuLayoutParams.leftMargin;
			// 根据传入的速度来滚动界面，当滚动到达左边界或右边界时，跳出循环。
			while (true) {
				leftMargin = leftMargin + speed[0];
				if (leftMargin >= 0) {
					leftMargin = 0;
					break;
				}
				if (leftMargin < mLeftEdge) {
					leftMargin = mLeftEdge;
					break;
				}
				publishProgress(leftMargin);
				try {
					Thread.sleep(15);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if (speed[0] > 0) {
				mIsMenuVisible = true;
			} else {
				mIsMenuVisible = false;
			}
			return leftMargin;
		}

		@Override
		protected void onProgressUpdate(Integer... leftMargin) {
			mMenuLayoutParams.leftMargin = leftMargin[0];
			mMenuLayout.setLayoutParams(mMenuLayoutParams);
		}

		@Override
		protected void onPostExecute(Integer leftMargin) {
			mMenuLayoutParams.leftMargin = leftMargin;
			mMenuLayout.setLayoutParams(mMenuLayoutParams);
		}
	}
}
